#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/06/08 17:29
# @Author  : elegantfrog
# @FileName: logs.py

import logging
import os

from flask_request_id import RequestID
from flask import current_app

req = RequestID(current_app)

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"

COLORS = {
    'WARNING': GREEN,
    'INFO': WHITE,
    'DEBUG': BLUE,
    'CRITICAL': YELLOW,
    'ERROR': RED
}

root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
log_dir = os.path.join(root_dir, "logs")


class ColoredFormatter(logging.Formatter):
    def __init__(self, msg, use_color=True):
        logging.Formatter.__init__(self, msg)
        self.use_color = use_color
        self.level = None

    def format(self, record):
        levelname = record.levelname
        message = str(record.msg)
        funcName = record.funcName
        if self.use_color and levelname in COLORS:
            record.levelname = levelname
            record.msg = message
            record.funcName = funcName
            record.request_id = req.id
        self.level = levelname
        return logging.Formatter.format(self, record)


LOGFORMAT = "[%(request_id)s][%(asctime)s] [%(levelname)s] (%(filename)s:%(funcName)s:%(lineno)d) %(message)s"
LOG_LEVEL = logging.DEBUG
formatter = ColoredFormatter(LOGFORMAT)
log_file = os.path.join(log_dir, "autotest.log")
fh = logging.FileHandler(log_file, encoding="UTF-8")
#fh = logging.StreamHandler()
fh.setLevel(LOG_LEVEL)
fh.setFormatter(formatter)
logging.root.setLevel(LOG_LEVEL)


def Logging(name):
    log = logging.getLogger(name)
    log.setLevel(LOG_LEVEL)
    log.addHandler(fh)
    return log


if __name__ == '__main__':
    logger = Logging(__name__)
    logger.info(123123)
